import * as THREE from 'three'
import { ColorGUIHelper, DegRadHelper, makeXYZGUI } from './GUIHelper'
import { GUI } from 'three/addons/libs/lil-gui.module.min.js'

export const addSpotLight = function ({
  scene = window.threeScene,
  gui,
  color = 0xffffff,
  intensity = 1,
  distance = 1000,
  angle = Math.PI / 3,
  penumbra = 0,
  decay = 2,
  position = [0, 10, 0],
  target = [0, 0, 0],
} = {}) {
  const light = new THREE.SpotLight(color, intensity, distance, angle, penumbra, decay)
  light.position.set(...position)
  light.target.position.set(...target)
  scene.add(light)
  scene.add(light.target)

  if (gui) {
    const helper = new THREE.SpotLightHelper(light)
    scene.add(helper)

    const updateLight = () => {
      light.target.updateMatrixWorld()
      helper.update()
    }

    updateLight()

    const container = document.querySelector('.gui-list')
    const gui = new GUI({ title: 'spot light', container })
    gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color')
    gui.add(light, 'intensity', 0, 250, 1)
    gui.add(light, 'distance', 0, 40).onChange(updateLight)
    gui.add(new DegRadHelper(light, 'angle'), 'value', 0, 90).name('angle').onChange(updateLight)
    gui.add(light, 'penumbra', 0, 1, 0.01)

    makeXYZGUI(gui, light.position, 'position', updateLight)
    makeXYZGUI(gui, light.target.position, 'target', updateLight)
  }
  return light
}
